package com.wk.ums.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wk.ums.entity.Member;
import com.wk.ums.mapper.MemberMapper;
import com.wk.ums.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;

@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Override
    public Member queryUser(String username, String password) {

        /*根据用户名查询用户*/
        Member member = baseMapper.selectOne(new QueryWrapper<Member>().eq("username", username));

        /*判断用户是否存在*/
        if (member == null) {
            throw new RuntimeException("用户不存在");
        }

        //给用户输入的密码加盐加密
        String pwd = DigestUtils.md5Hex(password + member.getSalt());

        /*判断加盐加密后的密码和数据库中对应的密码是否一致*/
        if (!member.getPassword().equals(pwd)) {
            throw new RuntimeException("用户名或密码错误");
        }

        return member;
    }

    @Override
    public void register(Member member, String code) {
        //校验验证码
        if (code.equals("1234")) {
            //生成加密盐
            String salt = RandomStringUtils.random(10, true, true);
            member.setSalt(salt);

            //密码加盐加密
            member.setPassword(DigestUtils.md5Hex(member.getPassword() + salt));

            member.setGrowth(0);                //成长值
            member.setIntegration(0);           //积分
            member.setLevelId(1L);              //会员等级
            member.setStatus(1);                //启用状态
            member.setCreateTime(LocalDateTime.now());   //创建时间
            baseMapper.insert(member);
        }
    }

    @Override
    public Boolean checkData(String data, Integer type) {
        String param;
        switch (type) {
            case 1: param = "username"; break;
            case 2: param = "mobile"; break;
            case 3: param = "email"; break;
            default: return false;
        }
        return baseMapper.selectCount(new QueryWrapper<Member>().eq(param, data))==0;
    }
}
